package src.mysql;

import src.config.SysConfig;
import src.server.ScoreObj;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ScoreSqlHelper extends MysqlHelper {
    private final String scoreTableName = SysConfig.MYSQL_SCORE_TABLE_NAME;
    private final PreparedStatement addScoreStatement;
    private final PreparedStatement getScoreStatement;

    /**
     * 难度设置
     */
    public enum Difficulty {
        /**
         * 简单, 一般, 困难
         */
        E, N, H
    }

    public ScoreSqlHelper() throws SQLException {
        super();
        // 创建表格
        String createTableSql = "create table if not exists `" + scoreTableName + "` ("
                + "`username` varchar(50) not null,"
                + "`score` int unsigned not null,"
                + "`date` varchar(100) not null,"
                + "`difficulty` char(1) not null);";
        super.executeRaw(createTableSql);

        // 准备预编译语句
        String addScoreSql = "insert into " + scoreTableName + " (username, score, date, difficulty) values (?,?,?,?)";
        addScoreStatement = connection.prepareStatement(addScoreSql);
        String getScoreSql = "select * from `" + scoreTableName + "` where difficulty=? order by score desc limit ?";
        getScoreStatement = connection.prepareStatement(getScoreSql);
    }

    /**
     * 添加一个用户成绩数据
     *
     * @param username   用户名
     * @param score      分数
     * @param date       时间
     * @param difficulty 难度
     */
    public synchronized void addScore(String username, int score, String date, Difficulty difficulty) {
        try {
            addScoreStatement.setString(1, username);
            addScoreStatement.setInt(2, score);
            addScoreStatement.setString(3, date);
            addScoreStatement.setString(4, difficulty.name());
            System.out.println(addScoreStatement.toString());
            addScoreStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("添加用户成绩数据失败");
        }
    }

    public synchronized List<ScoreObj> getScore(Difficulty difficulty, int limit) {
        List<ScoreObj> ret = new ArrayList<ScoreObj>();
        try {
            getScoreStatement.setString(1, difficulty.name());
            getScoreStatement.setInt(2, limit);
            ResultSet resultSet = getScoreStatement.executeQuery();
            int i = 1;
            while (resultSet.next()) {
                String username = resultSet.getString("username");
                int score = resultSet.getInt("score");
                String date = resultSet.getString("date");
                ret.add(new ScoreObj(i, username, score, date));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
}
